package com.jghz.transfer.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.client.RestTemplate;

import com.jghz.framework.utils.SpringHolder;
import com.jghz.transfer.entity.Logink;
import com.jghz.transfer.entity.UserTokenResult;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.dao.IMessageTransporterDAO;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.factory.ITransportClientFactory;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.impl.USendRequset;
import com.wondersgroup.cuteinfo.client.exchangeserver.exchangetransport.impl.USendResponse;
import com.wondersgroup.cuteinfo.client.util.SSLUtils;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class LoginkService {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	private static final String USERTOKEN_VERY_URL = "https://ssl.logink.org/authapi/rest/auth/verify";

	/**
	 * 验证token
	 *
	 * @throws Exception
	 */
	public static void checkToken() throws Exception {
		Logink logink = SpringHolder.getBean("logink");
		String token = logink.getUserToken().getTokenID().replaceAll("ticket:", "");
		SSLUtils.ignoreSsl();// 免去ssl证书
		StringBuilder restUrl = new StringBuilder(USERTOKEN_VERY_URL)
				.append("?applicantToken={applicantToken}&userToken={userToken}&resource={resourceId}");
		RestTemplate restTemplate = new RestTemplate();
		UserTokenResult utr = restTemplate.getForObject(restUrl.toString(), UserTokenResult.class, token, token,
				logink.getResourceId());
		if (!utr.getTokenValied()) {
			logink.setUserToken(Logink.generateToken(logink.getUsername(), logink.getPassword(), logink.getResourceId(),
					logink.getAuthURL()));
			log.info("token令牌失效，重新获取新的：{}", logink.getUserToken().getTokenID());
		}
	}

	public static boolean sendXml(String actionType, String xml) {
		Logink logink = SpringHolder.getBean("logink");

		// new USendRequset
		USendRequset sendReq = new USendRequset();
		sendReq.setToaddress(logink.getToaddress().split(","));
		// 设置待发送的业务报文
		sendReq.setSendRequestTypeXML(actionType, xml);

		IMessageTransporterDAO transporter = null;
		Date startTime = null;// 传输开始时间
		Date endtTime = null;// 传输结束时间
		StringBuilder sb = new StringBuilder();
		try {
			startTime = new Date();
			// 最后，调用平台提供的发送服务发送报文
			transporter = ITransportClientFactory.createMessageTransporter(logink.getUserToken(),
					logink.getTargetURL());
			USendResponse response = transporter.send(sendReq);

			if (response.isSendResult()) {
				endtTime = new Date();
				sb.append("本次报文发送成功，开始时间：").append(DATE_FORMAT.format(startTime)).append("，结束时间：")
						.append(DATE_FORMAT.format(endtTime)).append("，本次耗时：")
						.append(endtTime.getTime() - startTime.getTime()).append("毫秒").append("\n").append("本次报文长度：")
						.append(xml.getBytes().length).append("，报文内容如下：").append("\n").append(xml);
				log.info(sb.toString());
				return true;
			} else {
				endtTime = new Date();
				// 错误的情况下，会返回异常代码以及异常信息。异常代码请参照《3.2 共建指导性文件：交换接入》中的异常代码信息
				sb.append("本次报文发送失败").append("开始时间：").append(DATE_FORMAT.format(startTime)).append("，结束时间：")
						.append(DATE_FORMAT.format(endtTime)).append("，本次耗时：")
						.append(endtTime.getTime() - startTime.getTime()).append("毫秒").append("\n").append("失败原因如下：")
						.append(response.getGenericFault().getMessage()).append("\n").append("本次报文长度：")
						.append(xml.getBytes().length).append("，报文内容如下：").append("\n").append(xml);
				log.error(sb.toString());

				return false;
			}
		} catch (Exception e) {
			endtTime = new Date();
			sb.append("本次报文发送失败").append("开始时间：").append(DATE_FORMAT.format(startTime)).append("，结束时间：")
					.append(DATE_FORMAT.format(endtTime)).append("，本次耗时：")
					.append(endtTime.getTime() - startTime.getTime()).append("毫秒").append("\n").append("程序异常，请查看异常：")
					.append(e.getMessage()).append("\n").append("本次报文长度：").append(xml.getBytes().length)
					.append("，报文内容如下：").append("\n").append(xml);
			log.error(sb.toString(), e);
			return false;
		}
	}

}
